/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedLineData } from '@amcax/base';
import {
  isPolylinePlanar,
  isPolylineStraight,
} from '@app-base/common/utils/lines-coplanar';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { MessageTip } from '@app-cad/common/utils/MessageTip';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { useEffect, useState } from 'react';
import { usePlaneContext } from './PlaneContext';
import { ChildPlaneCommandProps } from './types';

type FormData = {
  curve?: pickedLineData;
};

type Params = {
  mode: 'planeCurve';
  curve: string;
};

// 创建平面-通过平面曲线
export const PlaneCurve = ({
  props,
  onClose,
  editDxid,
}: ChildPlaneCommandProps) => {
  const [formData, setFormData] = useState<FormData>({});
  const { sharedCurve, setSharedCurve } = usePlaneContext();

  const { picker } = useTools();

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData({});
      return;
    }

    const { curve } = props.params as Params;

    await initEditDependency([curve]);

    const curveObj = picker.generatePickObjByPickID(curve) as pickedLineData;

    setFormData({
      curve: curveObj,
    });

    // 仅 line1 为共享线
    setSharedCurve(curveObj);
  }, [editDxid]);

  useEffect(() => {
    if (sharedCurve && !formData.curve) {
      setFormData((prev) => ({ ...prev, curve: sharedCurve }));
    }
  }, [sharedCurve]);

  const isFormDataValid = (showTip = false) => {
    const { curve } = formData;

    if (curve == null) {
      return false;
    }

    if (isPolylineStraight(curve.edgeData)) {
      if (showTip) MessageTip.warning('不能输入直线');
      return false;
    }

    if (!isPolylinePlanar(curve.edgeData)) {
      if (showTip)
        MessageTip.warning('输入的曲线不是平面的，请选择一条平面曲线');
      return false;
    }

    return true;
  };

  useAsyncEffect(async () => {
    if (!isFormDataValid(true)) {
      clear();
      return;
    }

    await execute(true);
  }, [formData]);

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid(true)) {
      return;
    }

    await execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, clear, confirmCommand, isLoading } =
    useCommand('cmd-plane-curve', {
      commandName: 'CreatePlane',
      editDxid,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const execute = (preview: boolean) => {
    const { curve } = formData;

    return confirmCommand(
      {
        a: {
          mode: 'planeCurve',
          curve: curve.edgeId,
        },
      },
      preview,
    );
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      curve: {
        type: 'string',
        format: PickInputRJSFFormat.PickCurve,
      },
    },
  };

  return (
    <NonDialogPickableCommandForm
      className='-mt-3'
      disabled={initingEdit}
      onCancel={onClose}
      submitLoading={isLoading}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        if (v.curve && v.curve !== formData.curve) {
          setSharedCurve(v.curve);
        }

        setFormData(v);
      }}
      extraUiSchema={{
        curve: {
          'ui:placeholder': '请输入曲线',
          'ui:autofocus': true,
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
};
